<template>
    <div>
        <van-field v-model="yzm" center clearable label="短信验证码" placeholder="请输入短信验证码">
            <template #button>
                <van-button :disabled="btnFlag" size="small" type="primary" @click="sendMsg">{{ txt }}</van-button>
            </template>
        </van-field>

        <div class="loginbtn">
            <van-button :disabled="flag" round block type="danger" @click="next">下一步</van-button>
        </div>
    </div>
</template> 

<script>
import { doSendMsgCode, doCheckCode } from '../../api/user'
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);
export default {
    data() {
        return {
            yzm: '',
            txt: "发送验证码",
            time: 60,
            btnFlag: false
        }
    },
    methods: {
        sendMsg() {
            const timer = setInterval(() => {
                this.time--
                if (this.time == 0) {
                    clearInterval(timer)
                    this.btnFlag = false
                    this.txt = '发送验证码'
                    this.time = 60
                } else {
                    this.txt = this.time + 's后重新发送'
                    this.btnFlag = true
                }
            }, 1000)
            setTimeout(() => {
                doSendMsgCode({tel:localStorage.getItem("tel")}).then(res => {
                    console.log(res.data);
                    this.yzm = res.data.data
                })
            }, 2500)

        },
        next() {
            doCheckCode({ tel: localStorage.getItem("tel"),telcode:this.yzm}).then(res => {
                console.log(res);
                if (res.data.code == 200) {
                    this.$router.push('/register/three')
                } else {
                    Toast('验证码错误');
                }
            })
        }
    },
    computed: {
        flag() {
            if (/^\d{5}$/.test(this.yzm)) {
                return false
            } else {
                return true
            }
        }
    }
}
</script>

<style scoped>
.loginbtn {
    width: 80%;
    margin: 20px auto;
}
</style>